package com.pluszg.nutrition.product.service.impl;

import com.pluszg.nutrition.database.mapper.product.ProductMapper;
import com.pluszg.nutrition.common.exception.PlusBusinessException;
import com.pluszg.nutrition.model.product.Product;
import com.pluszg.nutrition.product.service.ProductService;
import com.pluszg.nutrition.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@Transactional
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product add(Product product) {
        log.info("商品添加方法");
        product.setId(RandomUtil.generateUUID());
        productMapper.insert(product);
        return product;
    }

    @Override
    public Product findById (String id) {
        log.info("商品查询方法");
        return productMapper.loadById(id).orElseThrow(()-> new PlusBusinessException("未找到商品信息"));
    }

    @Override
    public List<Product> list (Product product) {
        log.info("商品查询列表");
        return productMapper.list(product);
    }

    @Override
    public Product modify (Product product) {
        log.info("商品修改方法");
        productMapper.update(product);
        return product;
    }

    @Override
    public Boolean delete (String id){
        log.info("商品删除方法");
        productMapper.deleteById(id);
        return Boolean.TRUE;
    }

    @Override
    public void deduct (String productId, Integer deductCount){
        Product product = this.findById(productId);
        if (ObjectUtils.isEmpty(product)) {
            throw new PlusBusinessException("商品信息不能为空");
        }
        int surplus = product.getCount() - deductCount;
        if (surplus < 0) {
            throw new PlusBusinessException("商品库存不足");
        }
        product.setCount(surplus);
        productMapper.update(product);
    }
}
